﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using System.Collections;
using LookupFieldEntityPicker.Helpers;

namespace LookupFieldEntityPicker.CustomLookup
{
    public class RecordPickerDialog : PickerDialog
    {

        private SPList _list = null;
        private List<String> columnsList = new List<string>() { Constants.DEPARTMENT_CODE, Constants.DEPARTMENT_NAME, Constants.DEPARTMENT_DESCRIPTION };

        public RecordPickerDialog()
            : base(new RecordPickerQueryControl(), new TableResultControl(), new RecordPicker())
        {
            var customProperty = System.Web.HttpContext.Current.Request["CustomProperty"];

            //RecordPicker picker = base.EditorControl as RecordPicker;
            //string anotherWay = picker.CustomProperty;

            if (customProperty != null)
            {
                CustomProperty = customProperty;
            }
        }

        internal SPList List
        {
            get
            {
                if (_list == null)
                    _list = SPContext.Current.Web.GetList(Constants.LOOKUP_LIST_URL);
                return _list;
            }
        }
       
        protected override void OnPreRender(EventArgs e)
        {
            TableResultControl tableResultControl = (TableResultControl)base.ResultControl;
            ArrayList columnDisplayNames = tableResultControl.ColumnDisplayNames;
            ArrayList columnNames = tableResultControl.ColumnNames;
            ArrayList columnWidths = tableResultControl.ColumnWidths;
            
            int percentage = 100 / columnsList.Count;
            foreach (string fieldName in columnsList)
            {
                this.CreateResultColumn(columnDisplayNames, columnNames, columnWidths, percentage, fieldName);
            }

            base.OnPreRender(e);
        }

        private void CreateResultColumn(ArrayList columnDisplayNames, ArrayList columnNames, ArrayList columnWidths, int percentage, string fieldName)
        {
            SPField field = List.Fields.GetFieldByInternalName(fieldName);
            columnDisplayNames.Add(field.Title);
            columnNames.Add(fieldName);
            columnWidths.Add(string.Format("{0}%", percentage));
        }
    }
}
